package com.hs.thread.lock;

import com.hs.thread.communication.wait.comsummer.P;

import java.lang.management.ThreadInfo;

/**
 * Created by husheng02.
 *
 * @author <a href="mailto:husheng3921@163.com">胡圣</a>
 * @date 2020/08/08 12:45
 */
public class DiningPhilosophers {
    public static class Philosopher implements Runnable{
        private Object leftChopstick;
        private Object rightChopstick;

        public Philosopher(Object leftChopstick, Object rightChopstick){
            this.leftChopstick = leftChopstick;
            this.rightChopstick = rightChopstick;
        }
        @Override
        public void run() {
            try{
                while (true){
                    doAction("思考人生、宇宙");
                    synchronized (leftChopstick){
                        doAction("拿起左手筷子");
                        synchronized (rightChopstick){
                            doAction("拿起右手筷子");
                            doAction("吃饭");
                            doAction("放下右手筷子");
                        }
                        doAction("放下左手的筷子");
                    }
                }
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
        private void doAction(String action) throws InterruptedException{
            System.out.println(Thread.currentThread().getName()+" "+action);
            Thread.sleep((long)(Math.random()*10));
        }
    }

    public static void main(String[] args) {
        Philosopher[] philosophers = new Philosopher[5];
        Object[] chopsticks = new Object[philosophers.length];
        for(int i = 0; i  < chopsticks.length; i++){
            chopsticks[i] = new Object();
        }
        for (int i = 0; i < philosophers.length;i++){
            Object leftChopstick = chopsticks[i];
            Object rightChopstick = chopsticks[(i+1)% chopsticks.length];
            philosophers[i] = new Philosopher(rightChopstick, leftChopstick);
            new Thread(philosophers[i],"哲学家"+(i+1)+"号").start();
        }
    }
}
